package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.OrderInfoVo;
import com.atguigu.paymentdemo.entity.OrderInfo;
import com.atguigu.paymentdemo.entity.PaymentInfo;
import com.atguigu.paymentdemo.entity.Product;
import com.atguigu.paymentdemo.enums.OrderStatus;
import com.atguigu.paymentdemo.mapper.OrderInfoMapper;
import com.atguigu.paymentdemo.service.OrderInfoService;
import com.atguigu.paymentdemo.service.PaymentInfoService;
import com.atguigu.paymentdemo.service.ProductService;
import com.atguigu.paymentdemo.utils.OrderNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private ProductService productService;

    @Resource
    private PaymentInfoService paymentInfoService;

    /**
     * 创建订单
     *
     * @param productId
     * @return
     */
    @Override
    public OrderInfo createOrderByProductId(Long productId, String type) {

        // 查找已存在未支付的订单(接口幂等性)
        OrderInfo order = getNoPayOrderByProductId(productId);

        // 判断是否为空
        if (order != null) {
            return order;
        }

        // 获取商品id
        Product product = productService.getById(productId);

        // 生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTitle(product.getTitle());
        // 订单号
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo());
        orderInfo.setProductId(productId);
        orderInfo.setTotalFee(product.getPrice()); // 单位：分
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
        orderInfo.setUserId(666L);
        if(type == "weixin") {
            orderInfo.setPaymentType("微信");
        } else {
            orderInfo.setPaymentType("支付宝");
        }

        save(orderInfo);

        return orderInfo;
    }

    /**
     * 保存支付扫描二维码
     *
     * @param orderNo
     * @param codeUrl
     */
    @Override
    public void saveCodeUrl(String orderNo, String codeUrl) {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCodeUrl(codeUrl);
        // 进行修改
        update(orderInfo, lambdaQueryWrapper);
    }

    /**
     * 订单列表
     *
     * @return
     */
    @Override
    public List<OrderInfo> listOrderByCreateTimeDesc() {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> list = list(lambdaQueryWrapper);
        /*if (list != null && list.size() > 0) {
            List<OrderInfoVo> collect = list.stream().map(item -> {
                OrderInfoVo orderInfoVo = new OrderInfoVo();
                BeanUtils.copyProperties(item, orderInfoVo);
                String orderNo = item.getOrderNo();
                // 根据订单号查询到这个用户的支付类型
                PaymentInfo paymentInfo = paymentInfoService.getPaymentTypeByOrderNo(orderNo);
                if (paymentInfo != null) {
                    orderInfoVo.setPaymentType(paymentInfo.getPaymentType());
                }
                return orderInfoVo;
            }).collect(Collectors.toList());
            return collect;
        }*/
        return list;
    }

    /**
     * 更新订单状态
     *
     * @param orderNo
     * @param orderStatus
     */
    @Override
    public void updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        log.info("更新订单状态 ===> {}", orderStatus.getType());
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderStatus(orderStatus.getType());

        update(orderInfo, lambdaQueryWrapper);
    }

    /**
     * 处理重复的通知
     *
     * @param orderNo
     * @return
     */
    @Override
    public String getOrderStatus(String orderNo) {

        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo one = getOne(lambdaQueryWrapper);
        if (one == null) {
            return null;
        }
        return one.getOrderStatus();
    }

    /**
     * 查询创建超过5分钟，并且没有支付的订单
     *
     * @param minutes
     * @return
     */
    @Override
    public List<OrderInfo> getNoPayOrderByDuration(int minutes) {
        // 得到5分钟之前的时间
        Instant minus = Instant.now().minus(Duration.ofMinutes(minutes));

        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 没有支付的
        lambdaQueryWrapper.eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType());
        // 超过5分钟的
        lambdaQueryWrapper.le(OrderInfo::getCreateTime, minus);

        List<OrderInfo> list = list(lambdaQueryWrapper);
        return list;

    }

    /**
     * 根据订单号获取订单信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        return getOne(lambdaQueryWrapper);

    }

    /**
     * 根据productId来查找是否存在这个订单
     *
     * @param productId
     * @return
     */
    private OrderInfo getNoPayOrderByProductId(Long productId) {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getProductId, productId);
        // 状态必须是没有支付的
        lambdaQueryWrapper.eq(OrderInfo::getOrderStatus, OrderStatus.NOTPAY.getType());
        // 下面还需要判断用户是否存在(固定了的)
        lambdaQueryWrapper.eq(OrderInfo::getUserId, 666L);
        OrderInfo one = getOne(lambdaQueryWrapper);
        return one;
    }
}
